/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package panel;

import dao.DetalleventaDao;
import dao.SedeDao;
import dao.TransportistaDao;
import dao.VentaDao;
import dto.Detalleventa;
import dto.Sede;
import dto.Transportista;
import dto.Venta;
import factory.FactoryDao;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;

/**
 *
 * @author Sistemas
 */
public class JFVentas extends javax.swing.JFrame {

    private Hashtable<Integer, Detalleventa> detalle;

    /**
     * Creates new form JFPantalla
     */
    public JFVentas() {
        detalle = new Hashtable<>();
        initComponents();
        init();
        
        //con.ejecutar(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jBAceptar = new javax.swing.JButton();
        jBCancelar = new javax.swing.JButton();
        btnAgregarProducto = new javax.swing.JButton();
        txtFecha = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        boxSede = new javax.swing.JComboBox();
        boxTransportista = new javax.swing.JComboBox();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Compra de Productos");

        jLabel1.setText("Transportista:");

        jLabel2.setText("Tipo de Venta:");

        jLabel3.setText("Fecha:");

        jTable1.setModel(new TableModelDetalle(getListaDetalle()));
        jScrollPane1.setViewportView(jTable1);

        jBAceptar.setText("Aceptar Compra");
        jBAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBAceptarActionPerformed(evt);
            }
        });

        jBCancelar.setText("Cancelar Compra");
        jBCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBCancelarActionPerformed(evt);
            }
        });

        btnAgregarProducto.setText("Agregar Producto");
        btnAgregarProducto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarProductoActionPerformed(evt);
            }
        });

        jLabel4.setText("Sede:");

        boxTransportista.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boxTransportistaActionPerformed(evt);
            }
        });

        jRadioButton1.setText("Contado");

        jRadioButton2.setText("Credito");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jBAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jBCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(boxTransportista, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jRadioButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jRadioButton2)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(boxSede, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnAgregarProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(boxTransportista, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jRadioButton1)
                        .addComponent(jRadioButton2))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(boxSede, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4)))
                .addGap(10, 10, 10)
                .addComponent(btnAgregarProducto)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBAceptar)
                    .addComponent(jBCancelar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBAceptarActionPerformed
        
        Transportista objTransportista = (Transportista) boxTransportista.getSelectedItem();
        if(objTransportista == null){
            mensaje("Debe seleccionar un transportista");
            return;
        }
        
        Sede objSede = (Sede) boxSede.getSelectedItem();
        if(objSede == null){
            mensaje("Debe seleccionar una Sede");
            return;
        }
        
        String tipoVenta = jRadioButton1.isSelected() ? "Contado" : "Credito";
        String fecha = txtFecha.getText();
        String fechaPago = jRadioButton1.isSelected() ? txtFecha.getText() : null;
        
        double monto = 0;
        Enumeration<Detalleventa> enumeration = this.detalle.elements();
        while (enumeration.hasMoreElements()) {
            Detalleventa objDetalle =  enumeration.nextElement();
            monto += objDetalle.getPrecio() * objDetalle.getCantidad();
        }
        
        
        Venta objVenta = new Venta();
        objVenta.setIcitransportista(objTransportista.getIcitransportista());
        objVenta.setIidsede(objSede.getIidsede());
        objVenta.setSfecha(fecha);
        objVenta.setStipoventa(tipoVenta);
        objVenta.setImonto(monto);
        objVenta.setSfechadepago(fechaPago);
        
        FactoryDao factory = FactoryDao.getFactoryInstance();
        VentaDao ventaDao = factory.getNewVentaDao();
        ventaDao.setObjDto(objVenta);
        
        try {
            ventaDao.update();
        } catch (Exception ex) {
            mensaje("Error al insertar");
            return;
        }
        
        System.out.println(objVenta.getIidventa());
        
        if(objVenta.getIidventa() == 0){
            mensaje("Error al insertar");
            return;
        }
        boolean conError = false;
        DetalleventaDao detalleVentaDao = factory.getNewDetalleventaDao();
        enumeration = this.detalle.elements();
        while (enumeration.hasMoreElements()) {
            Detalleventa objDetalle =  enumeration.nextElement();
            objDetalle.setIidventa(objVenta.getIidventa());
            detalleVentaDao.setObjDto(objDetalle);
            try {
                detalleVentaDao.update();
            } catch (Exception ex) {
                conError = true;
            }
        }
        
        if(!conError){
            mensaje("La venta se realizo exitosamente");
            jBAceptar.setEnabled(false);
            jBCancelar.setText("Cerrar");
            jRadioButton1.setEnabled(false);
            jRadioButton2.setEnabled(false);
            boxSede.setEnabled(false);
            boxTransportista.setEnabled(false);
            btnAgregarProducto.setEnabled(false);
        }else{
            mensaje("Ocurrio un error al realizar la Venta");
        }
    }//GEN-LAST:event_jBAceptarActionPerformed

    private void boxTransportistaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boxTransportistaActionPerformed
        
        
        
    }//GEN-LAST:event_boxTransportistaActionPerformed

    private void btnAgregarProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarProductoActionPerformed
        JFProducto producto = new JFProducto(this);
        producto.setLocationRelativeTo(this);
        producto.setVisible(true);
    }//GEN-LAST:event_btnAgregarProductoActionPerformed

    private void jBCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBCancelarActionPerformed
        dispose();
        System.exit(0);
    }//GEN-LAST:event_jBCancelarActionPerformed

    public void insertarProductoDetalle(Detalleventa detalleProducto) {        
        this.detalle.put(detalleProducto.getIidproducto(), detalleProducto);
        updateTable();
    }
    
    private void mensaje(String msg){
        JOptionPane.showMessageDialog(this, msg);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JFVentas().setVisible(true);
            }
        });
    }

    public Vector<Detalleventa> getListaDetalle() {
        Vector<Detalleventa> lista = new Vector<>();
        Enumeration<Detalleventa> enumeration = this.detalle.elements();
        while (enumeration.hasMoreElements()) {
            lista.add(enumeration.nextElement());
        }

        return lista;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox boxSede;
    private javax.swing.JComboBox boxTransportista;
    private javax.swing.JButton btnAgregarProducto;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jBAceptar;
    private javax.swing.JButton jBCancelar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    public javax.swing.JRadioButton jRadioButton1;
    public javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField txtFecha;
    // End of variables declaration//GEN-END:variables

    private void init() {
        FactoryDao factory = FactoryDao.getFactoryInstance();
        TransportistaDao dao = factory.getNewTransportistaDao();
        SedeDao daosede = factory.getNewSedeDao();
        Vector<Sede> listaSede = daosede.selectTodos();
        Vector<Transportista> listaTransportista = dao.selectTodos();
        Iterator<Transportista> it = listaTransportista.iterator();
        Iterator<Sede> it2 = listaSede.iterator();
        while (it.hasNext()) {
            boxTransportista.addItem(it.next());
        }
        while (it2.hasNext()) {
            boxSede.addItem(it2.next());
        }

        ButtonGroup btngrup = new ButtonGroup();
        btngrup.add(jRadioButton1);
        btngrup.add(jRadioButton2);
        jRadioButton1.setSelected(true);

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        txtFecha.setText(dateFormat.format(date));
        txtFecha.setEditable(false);
        
        jTable1.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                
                if(e.getButton() != MouseEvent.BUTTON3 || jTable1.getSelectedRow() < 0 || !btnAgregarProducto.isEnabled())
                    return;
                
                final JPopupMenu popupMenu = new JPopupMenu();
                JMenuItem deleteItem = new JMenuItem("Eliminar");
                deleteItem.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        int row = jTable1.getSelectedRow();
                        TableModelDetalle model = (TableModelDetalle)jTable1.getModel();
                        Detalleventa obj = model.getDetalleFromRow(row);
                        
                        detalle.remove(obj.getIidproducto());
                        updateTable();
                    }
                });
                popupMenu.add(deleteItem);
                popupMenu.show(jTable1, e.getX(), e.getY());
            }

        });

        setLocationRelativeTo(null);
    }
    
    private void updateTable(){
        jTable1.setModel(new TableModelDetalle(getListaDetalle()));
        jTable1.updateUI();
    }
    
}
